package com.wink.admin.security;


import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import com.wink.admin.utils.ThreadLocalUtils;
import com.wink.admin.utils.TokenUtils;
import org.slf4j.MDC;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 授权拦截器
 *
 * @author donaldhan
 */
public class JwtAuthenticationFilter extends OncePerRequestFilter {


    @Override
    public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        MDC.put("requestId", IdUtil.fastSimpleUUID());
        //校验token
        //  TODO: 2020/11/9 WINK 可以校验权限暂不实现了
        Object o = TokenUtils.tokenAuthentication(token, TokenUtils.secret);
        JSONObject jsonObject = new JSONObject(o);
        ThreadLocalUtils.setObject(jsonObject);
        Authentication authentication = new UsernamePasswordAuthenticationToken("principal", null, null);
        SecurityContextHolder.getContext().setAuthentication(authentication);

        filterChain.doFilter(request, response);
    }
}
